<template>
  <div id="space-detail">
    <!-- 顶部展示 -->
    <a-flex justify="space-between">
      <div class="title-space">
        <h2 style="font-weight: bold; font-size: 26px; margin-top: 16px">
          {{ space.spaceName }}
          <QuestionCircleOutlined style="font-size: 16px" @click="doShowIntroduction" />
        </h2>
      </div>
      <!-- 按钮区域 (这边跳转要带上spaceId，用于区分创建图片的目的地) -->
      <div class="button-space">
        <a-space align="center">
          <!-- 进度条 -->
          <a-tooltip
            :title="`占用空间 ${formatSize(space.totalSize)} / ${formatSize(space.maxSize)}`"
          >
            <a-progress
              type="circle"
              :percent="
                (((space.totalSize as number) * 100) / (space.maxSize as number)).toFixed(1)
              "
              :size="32"
              style="margin: 4px 12px 0 0"
            />
          </a-tooltip>
          <!-- 上传图片 -->
          <a-button
            v-if="canUploadPicture"
            :icon="h(PlusOutlined)"
            type="primary"
            shape="round"
            :href="`/picture/add?spaceId=${id}`"
            style="margin-right: 4px; font-weight: bold; background-color: #4caf50"
          >
            上传图片
          </a-button>
          <!-- 空间成员管理 -->
          <a-button
            v-if="canManageSpaceUser && SPACE_TYPE_ENUM.TEAM === space.spaceType"
            :icon="h(TeamOutlined)"
            type="primary"
            shape="round"
            :href="`/spaceUserManage/${id}`"
            style="
              margin-right: 4px;
              font-weight: bold;
              background-color: rgba(213, 127, 151, 0.94);
            "
          >
            成员管理
          </a-button>
          <!-- 空间分析 -->
          <a-button
            v-if="canManageSpaceUser"
            :icon="h(BarChartOutlined)"
            type="primary"
            shape="round"
            :href="`/space/analyze?spaceId=${space.id}`"
            style="margin-right: 4px; font-weight: bold; background-color: #0db4b6"
          >
            空间分析
          </a-button>
          <!-- 批量编辑 -->
          <a-button
            v-if="canEditPicture"
            :icon="h(EditOutlined)"
            type="primary"
            shape="round"
            style="margin-right: 4px; font-weight: bold; background-color: blueviolet"
            @click="doShowBatchEditModal"
          >
            批量编辑
          </a-button>
          <!-- 按颜色搜索 - 颜色选择器 -->
          <a-form-item class="color-picker">
            <color-picker format="hex" @pureColorChange="onColorChange" />
          </a-form-item>
        </a-space>
      </div>
    </a-flex>

    <!-- 搜索表单展示 -->
    <pictureSearchForm :onSearch="doSearch"></pictureSearchForm>

    <!-- 图片展示 -->
    <div>
      <PictureList
        :dataList="dataList"
        :loading="loading"
        style="margin: 12px 0"
        :showOption="true"
        :onReload="fetchData"
        :canEdit="canEditPicture"
        :canDelete="canDeletePicture"
      ></PictureList>
      <!-- 加载更多提示 -->
      <div v-if="loadingMore" class="loading-more">
        <a-spin size="middle" />
        <span style="margin-left: 8px">加载更多...</span>
      </div>
      <!-- 没有更多数据提示 -->
      <div v-if="!hasMore && !loading && !loadingMore" class="no-more">
        <a-result title="已经到底啦~" >
          <template #icon>
            <SmileTwoTone />
          </template>
        </a-result>
      </div>
    </div>

    <!--  已关闭分页插件，改为下滑刷新  -->
    <!--    &lt;!&ndash; 分页插件 &ndash;&gt;
        <div class="pagination-container">
          <a-pagination
            v-model:current="searchParams.current"
            :page-size-options="['10', '12', '16', '20']"
            :page-size="searchParams.pageSize"
            :total="total"
            @change="handlePageChange"
            show-size-changer
          />
        </div>-->

    <!-- 展示空间说明信息的对话框 -->
    <a-modal v-model:open="open" title="空间详情" :footer="null">
      <div class="space-detail">
        <!-- 头像及空间名称等信息区域 -->
        <div class="space-header">
          <a-avatar :size="64" style="background-color: #d9d9d9" :src="space.user?.userAvatar" />
          <div class="space-info">
            <h3 class="space-name">{{ space.spaceName ?? '默认空间' }}</h3>
            <p class="creator-info">
              创建者：{{ space.user?.userName ?? '未知' }}
              <a-tag style="margin-left: 4px" color="pink" :bordered="false">
                {{ space.user?.userRole === 'admin' ? '管理员' : '普通用户' }}
              </a-tag>
            </p>
          </div>
        </div>
        <!-- 统计信息卡片区域 -->
        <a-card class="statistic-card">
          <div class="statistic-list">
            <div class="statistic-item">
              <p class="value">{{ formatSize(space.totalSize) }}</p>
              <p class="label">已用空间</p>
            </div>
            <div class="statistic-item">
              <p class="value">{{ formatSize(space.maxSize) }}</p>
              <p class="label">总空间</p>
            </div>
            <div class="statistic-item">
              <p class="value">{{ space.totalCount }}</p>
              <p class="label">图片数量</p>
            </div>
            <div class="statistic-item">
              <p class="value">{{ space.maxCount }}</p>
              <p class="label">最大数量</p>
            </div>
          </div>
        </a-card>
        <!-- 其他详情信息区域 -->
        <div class="detail-info">
          <div class="info-item">
            <span class="info-label">空间ID：{{ space.id }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">空间类型：私有空间</span>
          </div>
          <div class="info-item">
            <span class="info-label"
              >空间等级
              <a-tag style="margin-left: 6px" color="pink">{{
                SPACE_LEVEL_MAP[space.spaceLevel as number]
              }}</a-tag>
            </span>
          </div>
          <div class="info-item">
            <span class="info-label"
              >创建时间：{{ dayjs(space.createTime).format('YYYY-MM-DD HH:mm:ss') }}</span
            >
          </div>
          <div class="info-item">
            <span class="info-label"
              >最近更新：{{ dayjs(space.editTime).format('YYYY-MM-DD HH:mm:ss') }}</span
            >
          </div>
        </div>
      </div>
    </a-modal>

    <!-- 批量编辑图片的对话框 -->
    <BatchEditPictureModal
      ref="batchEditPictureModalRef"
      :onSuccess="onBatchEditPictureSuccess"
      :spaceId="id as number"
      :pictureList="dataList"
    >
    </BatchEditPictureModal>
  </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'
import { computed, h, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { getSpaceVoByIdUsingGet } from '@/api/spaceController'
import { message } from 'ant-design-vue'
import { useLoginUserStore } from '@/stores/userLogin'
import {
  listPictureVoByPageUsingPost,
  searchPictureByColorUsingPost,
} from '@/api/pictureController'
import {
  QuestionCircleOutlined,
  AppstoreAddOutlined,
  EditOutlined,
  PlusOutlined,
  BarChartOutlined,
  TeamOutlined,
  SmileTwoTone,
} from '@ant-design/icons-vue'
import { formatSize } from '@/util'
import { SPACE_LEVEL_MAP, SPACE_PERMISSION_ENUM, SPACE_TYPE_ENUM } from '@/constants/space'
import dayjs from 'dayjs'
import PictureList from '@/components/PictureList.vue'
import PictureSearchForm from '@/components/PictureSearchForm.vue'
import { ColorPicker } from 'vue3-colorpicker'
import 'vue3-colorpicker/style.css'
import BatchEditPictureModal from '@/components/modal/BatchEditPictureModal.vue'

const route = useRoute()
const router = useRouter()

// 定义props，接收空间id
interface props {
  id: string | number
}

// 接收空间id
const props = defineProps<props>()

// ---------- 展示图片列表修改（改为滑动刷新） ----------
// 是否还有更多的数据
const hasMore = ref<boolean>(true)
// 防止重复请求的标志
let isProcessing = false
// 定义底部加载时的动画
const loadingMore = ref(false)

// ----------- 空间按钮权限控制 ---------
// 通用权限检查函数
function createPermissionChecker(permission: string) {
  return computed(() => {
    return (space.value.permissionList ?? []).includes(permission)
  })
}

// 定义权限检查
const canManageSpaceUser = createPermissionChecker(SPACE_PERMISSION_ENUM.SPACE_USER_MANAGE)
const canUploadPicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_UPLOAD)
const canEditPicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_EDIT)
const canDeletePicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_DELETE)

// ----------- 空间介绍说明 ---------------
const open = ref<boolean>(false)
// 弹出对话框
const doShowIntroduction = () => {
  fetchData()
  open.value = true
}

// --------- 颜色搜索 ------------
const onColorChange = async (color: string) => {
  const res = await searchPictureByColorUsingPost({
    picColor: color,
    spaceId: props.id as number,
  })
  if (res.data.code === 0 && res.data.data) {
    const data = res.data.data ?? []
    dataList.value = data
    total.value = data.length
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

// --------- 获取空间详情 -------------
const space = ref<API.SpaceVO>({})
// 根据空间id获取详情
const fetchSpaceById = async () => {
  try {
    const res = await getSpaceVoByIdUsingGet({
      id: props.id as number,
    })
    if (res.data?.code === 0 && res.data?.data) {
      space.value = res.data.data
    } else {
      message.error('加载空间详情失败: ' + res.data?.message)
    }
  } catch (error: any) {
    message.error('加载空间详情失败: ' + error.message)
  }
}

// --------- 获取图片列表 -------------
// 执行搜索方法
const doSearch = (newSearchParams: API.PictureQueryDTO) => {
  searchParams.value = {
    ...searchParams.value,
    ...newSearchParams,
    current: 1,
  }
  // 重置数据和状态
  dataList.value = []
  hasMore.value = true
  // 搜索结束后，刷新页面数据
  fetchData()
}

// 定义查询参数
const searchParams = ref<API.PictureQueryDTO>({
  current: 1,
  pageSize: 16, // 瀑布流每页显示更多内容
  // 排序条件
  sortField: 'createTime',
  sortOrder: 'descend',
})

// 定义数据源
const dataList = ref<API.PictureVO[]>([])
const total = ref(0)
const loading = ref(false)

// 调用api请求图片列表数据
const fetchData = async () => {
  // 判断是否需要加载更多数据
  const isLoadingMore = Number(searchParams.value.current) > 1
  if (isLoadingMore) {
    loadingMore.value = true
  } else {
    loading.value = true
  }
  // 如果正在处理请求，则直接返回，防止重复请求
  if (isProcessing) {
    return
  }
  isProcessing = true

  // 构建查询参数
  const params: API.PictureQueryDTO = {
    ...searchParams.value,
    // 携带空间id查询
    spaceId: props.id as number,
  }

  try {
    const res = await listPictureVoByPageUsingPost(params)
    if (res.data?.code === 0 && res.data?.data) {
      const newData = res.data.data.records || []
      total.value = res.data.data.total || 0

      // 加载更多数据时累加数据，首次加载时替换数据
      if (isLoadingMore) {
        dataList.value = [...dataList.value, ...newData]
      } else {
        dataList.value = newData
      }
      // 判断是否还有更多数据
      hasMore.value = dataList.value.length < total.value
    } else {
      message.error('数据获取失败,' + res.data?.message)
    }
  } catch (err) {
    message.error('请求异常')
  } finally {
    loading.value = false
    // 刷新完成，重置标志
    loadingMore.value = false
    isProcessing = false
  }
}

// 分页变化处理
const handlePageChange = (page: number, pageSize: number) => {
  searchParams.value.current = page
  searchParams.value.pageSize = pageSize
  fetchData()
}

// 获取当前登录用户
const loginUser = ref<API.UserVO>({})
const getLoginUser = async () => {
  const userLoginStore = useLoginUserStore()
  loginUser.value = userLoginStore.loginUser
}

// 页面滚动监听处理
const handleScroll = () => {
  // 避免重复请求、无更多数据或加载中时触发
  if (loading.value || loadingMore.value || !hasMore.value || isProcessing) {
    return
  }

  // 计算页面滚动位置：距离底部小于 200px 时加载更多
  const scrollTop = window.scrollY || document.documentElement.scrollTop
  const clientHeight = document.documentElement.clientHeight || window.innerHeight
  const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight

  if (scrollTop + clientHeight >= scrollHeight - 100) {
    // 滚动到底部附近，加载更多
    searchParams.value.current = (searchParams.value.current ?? 0) + 1
    fetchData()
  }
}

// 页面挂载时获取空间信息
onMounted(() => {
  // 获取当前空间信息
  fetchSpaceById()
  // 获取当前登录用户信息
  getLoginUser()
  // 获取图片列表数据
  fetchData()
  // 监听页面滚动事件
  window.addEventListener('scroll', handleScroll)
})

// 页面卸载时移除滚动监听（防止内存泄漏）
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})

/**
 * 当路由发生变化时，重新获取空间图片列表数据
 */
watch(
  () => props.id,
  () => {
    // 获取当前空间信息
    fetchSpaceById()
    // 获取图片列表数据
    fetchData()
  },
)

// ---------- 批量编辑区域 --------------
// 分享弹窗引用
const batchEditPictureModalRef = ref()

// 批量编辑成功后，刷新数据
const onBatchEditPictureSuccess = () => {
  // 刷新数据
  fetchData()
}

// 点击批量编辑按钮，展示对话框
const doShowBatchEditModal = () => {
  if (batchEditPictureModalRef.value) {
    batchEditPictureModalRef.value.openModal()
  }
}
</script>

<style scoped>
/* 页面整体容器样式 */
#space-detail {
  padding: 12px;
  background-color: #e1eedf;
  border-radius: 12px;
  min-height: 1200px;
}

/*对话框相关的样式*/
.space-detail {
  padding: 20px;
}

.space-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.space-info {
  margin-left: 16px;
}

.space-name {
  font-size: 18px;
  font-weight: bold;
  margin: 0 0 8px 0;
}

.creator-info {
  font-size: 15px;
  margin: 0;
  color: #666;
}

/* 美化颜色选择器本身 */
.color-picker {
  margin-top: 24px;
  width: 80px; /* 自定义宽度 */
  border-radius: 12px; /* 圆角 */
}

.statistic-card {
  margin-bottom: 20px;
}

.statistic-list {
  display: flex;
  justify-content: space-around;
}

.statistic-item {
  text-align: center;
}

.value {
  font-size: 16px;
  font-weight: bold;
  margin: 0 0 4px 0;
}

.label {
  margin: 0;
  color: #999;
}

.detail-info {
  line-height: 2;
}

.info-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.info-label {
  font-weight: bold;
  margin-right: 8px;
}

/* 分页控件样式：新添加部分 */
.pagination-container {
  margin: 40px auto 20px;
  text-align: right;
  padding: 0 10px;
}
</style>
